<template>
    <div class="j-input" :class="{ has: button }" v-bind="$attrs">
        <input class="j-input-txt" :disabled="disabled" :placeholder="placeholder" v-model="innerValue" @keydown.enter="onEnter" @input="updateValue" type="text" />
        <div class="j-input-btn" v-show="button" ref="btn" @click="onChange">{{ button }}</div>
        <div class="j-input-close" v-show="clear && !!modelValue" v-if="!disabled" @click="onClear" :style="closeStyle"></div>
        <div class="j-input-err" v-if="err">{{ err }}</div>
    </div>
</template>

<script lang="ts" setup>
import i18n from "@/locals";
import { ref, watch, onMounted, computed } from "vue";

const closeStyle = ref({});
const btn = ref<any>(null);
onMounted(() => {
    if (btn.value) {
        closeStyle.value = { right: btn.value.clientWidth + 10 + "px" };
    }
});

const onClear = () => {
    innerValue.value = "";
    emit("clear");
};

const props = defineProps({
    modelValue: String,
    button: String,
    placeholder: {
        type: String,
        default: i18n.global.t("message.JInput.a")
    },
    clear: {
        type: Boolean,
        default: true
    },
    disabled: {
        type: Boolean,
        default: false
    },
    err: String
});

const emit = defineEmits(["update:modelValue", "change", "enter", "clear"]);
const innerValue = ref(props.modelValue);

// 监听innerValue的变化，触发v-model更新
watch(
    () => innerValue.value,
    newValue => {
        emit("update:modelValue", newValue);
    }
);

watch(
    () => props.modelValue,
    newValue => {
        innerValue.value = newValue;
        // console.log("改变了", newValue)
    }
);

watch(
    () => innerValue.value,
    () => {
        if (props.button) {
            closeStyle.value = { right: btn.value.clientWidth + 10 + "px" };
        }
    }
);

// 更新innerValue的方法
const updateValue = (event: Event) => {
    innerValue.value = (event.target as HTMLInputElement).value;
    emit("change");
};

const onChange = () => {
    emit("change", innerValue.value);
};

const onEnter = () => {
    emit("enter", innerValue.value);
};
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
